package com.itheima.tlais_web_management.controller;

import com.itheima.tlais_web_management.pojo.Emp;
import com.itheima.tlais_web_management.pojo.Result;
import com.itheima.tlais_web_management.service.Empservice;
import com.itheima.tlais_web_management.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private Empservice empservice;

    @PostMapping("login")
    public Result login(@RequestBody Emp emp){
        log.info("根据 姓名、密码 查找员工：{}",emp);

        Emp emp1 = empservice.login(emp);

        //登录成功，则生成 JWT 令牌
        if (emp1 != null){
            Map<String,Object> claims = new HashMap<String, Object>();
            claims.put("id",emp1.getId());
            claims.put("name",emp1.getName());
            claims.put("username",emp1.getUsername());
            String jwt = JwtUtils.generateJwt(claims);

            return Result.success(jwt);
        }

        //登录失败，则不生成
        return emp1 != null ? Result.success() : Result.error("用户名或密码错误");
    }

}
